package com.hqd.ch03.v10.reader.xml.namespace.support;

import com.hqd.ch03.v10.reader.xml.namespace.NamespaceHandler;
import com.hqd.ch03.v10.reader.xml.namespace.NamespaceHandlerResolver;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class DefaultNamespaceHandlerResolver implements NamespaceHandlerResolver {
    public static final String DEFAULT_HANDLER_MAPPINGS_LOCATION = "META-INF/spring.handlers";
    private Map<String, NamespaceHandler> handlerMappings = new HashMap<>();

    public DefaultNamespaceHandlerResolver() {
        this.init();
    }

    protected void init() {
        Properties properties = new Properties();
        try {
            /**
             * 加载配置文件
             */
            properties.load(this.getClass().getClassLoader().getResourceAsStream(DEFAULT_HANDLER_MAPPINGS_LOCATION));
            Enumeration<Object> keys = properties.keys();
            while (keys.hasMoreElements()) {
                String uri = keys.nextElement().toString();
                String handlerClass = properties.getProperty(uri);
                /**
                 * 初始化配置的类
                 */
                NamespaceHandler handler = (NamespaceHandler) Class.forName(handlerClass).getConstructor().newInstance();
                handler.init();
                /**
                 * 放入缓存
                 */
                handlerMappings.put(uri, handler);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public NamespaceHandler resolve(String namespaceUri) {
        return this.handlerMappings.get(namespaceUri);
    }
}
